package com.plate.common.web.aspect;

import com.plate.common.web.domain.LoginVal;
import com.plate.common.web.utils.OauthUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

/**
 * @ClassName UpdateEntityAspect
 * @Description TODO
 * @Author jiaxd
 * @Date 2023年10月31日 20:25
 * @Version 1.0
 */


@Aspect
@Component
public class UpdateEntityAspect {

    @Pointcut("execution(* com.plate..*.*Service.isSave(..))")
    public void insertPointCut() {}

    @Around("insertPointCut()")
    public Object insertAround(ProceedingJoinPoint joinPoint) throws Throwable {
        LoginVal currentUser = OauthUtils.getCurrentUser();
        // 获取传入目标方法的参数
        Object arg = joinPoint.getArgs()[0];
        Field[] fields = arg.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if ("createBy".equals(field.getName())) {
                field.set(arg, Long.parseLong(currentUser.getUserId()));
            }
            if ("createTime".equals(field.getName())) {
                field.set(arg, LocalDateTime.now());
            }
            if ("updateBy".equals(field.getName())) {
                field.set(arg, Long.parseLong(currentUser.getUserId()));
            }
            if ("updateTime".equals(field.getName())) {
                field.set(arg, LocalDateTime.now());
            }
            if ("delFlag".equals(field.getName())) {
                field.set(arg, 0);
            }
        }
        return joinPoint.proceed();
    }

    @Pointcut("execution(* com.plate..*.*Service.isUpdate(..))")
    public void updatePointCut() {

    }

    @Around("updatePointCut()")
    public Object updateAround(ProceedingJoinPoint joinPoint) throws Throwable {
        LoginVal currentUser = OauthUtils.getCurrentUser();
        Object arg = joinPoint.getArgs()[0];
        Field[] fields = arg.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if ("updateBy".equals(field.getName())) {
                field.set(arg, Long.parseLong(currentUser.getUserId()));
            }
            if ("updateTime".equals(field.getName())) {
                field.set(arg, LocalDateTime.now());
            }
        }
        return joinPoint.proceed();
    }

}
